/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presentation.view;

import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import presentation.controller.ControlPanelMyAccount;
import presentation.controller.ControlPanelNotes;
import vo.GradesVO;
import vo.SubjectVO;

/**
 *
 * @author Joanna 8a
 */
public class PanelNotes extends javax.swing.JPanel implements Observer {

    /**
     * Creates new form PanelNotes
     *
     * @param opc si es 1: Ver Notas, si es 2: Modificar Notas
     */
    public PanelNotes(AuxiliarFrame parent, boolean ver) {
        this.parent = parent;
        initComponents();
        parent.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Clipboard Copy.png")).getImage());
        
        if (ver) {
            setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ver Notas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Light", 1, 14), java.awt.Color.darkGray));
            jButtonAddGrade.setVisible(false);
            jButtonDeleteGrade.setVisible(false);
            jButtonUpdateGrade.setVisible(false);

            jButtonBack.setVisible(true);
        } else {
            setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Modificar Notas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Light", 1, 14), java.awt.Color.darkGray));
            parent.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Document2.png")).getImage());
            jButtonAddGrade.setVisible(true);
            jButtonDeleteGrade.setVisible(true);
            jButtonUpdateGrade.setVisible(true);

            jButtonBack.setVisible(true);
        }
        fillComboBoxSubjects();
        fillTable(((SubjectVO) jComboBoxSubjects.getSelectedItem()).getGroups().get(0).getGrades());
        currentRow = -1;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelSubject = new javax.swing.JLabel();
        jComboBoxSubjects = new javax.swing.JComboBox();
        jScrollPaneNotesTable = new javax.swing.JScrollPane();
        jTableNotes = new javax.swing.JTable();
        jButtonBack = new javax.swing.JButton();
        jButtonAddGrade = new javax.swing.JButton();
        jButtonDeleteGrade = new javax.swing.JButton();
        jButtonUpdateGrade = new javax.swing.JButton();
        jLabelOverallGrade = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Calificaciones", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Light", 1, 14), java.awt.Color.darkGray)); // NOI18N

        jLabelSubject.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jLabelSubject.setText("Materia");

        jComboBoxSubjects.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jComboBoxSubjects.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Seleccione una materia--" }));
        jComboBoxSubjects.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxSubjectsActionPerformed(evt);
            }
        });

        jTableNotes.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jTableNotes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Calificación", "Ponderación (%)", "Tipo", "Total", "id"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Double.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableNotes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableNotesMouseClicked(evt);
            }
        });
        jScrollPaneNotesTable.setViewportView(jTableNotes);
        jTableNotes.getColumnModel().getColumn(4).setMinWidth(0);
        jTableNotes.getColumnModel().getColumn(4).setPreferredWidth(0);
        jTableNotes.getColumnModel().getColumn(4).setMaxWidth(0);

        jButtonBack.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Cancel.png"))); // NOI18N
        jButtonBack.setText("Volver");
        jButtonBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBackActionPerformed(evt);
            }
        });

        jButtonAddGrade.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonAddGrade.setIcon(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Health.png"))); // NOI18N
        jButtonAddGrade.setText("Añadir Calificación");
        jButtonAddGrade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddGradeActionPerformed(evt);
            }
        });

        jButtonDeleteGrade.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonDeleteGrade.setIcon(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Minus.png"))); // NOI18N
        jButtonDeleteGrade.setText("Eliminar Calificación");
        jButtonDeleteGrade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteGradeActionPerformed(evt);
            }
        });

        jButtonUpdateGrade.setFont(new java.awt.Font("Segoe UI Light", 0, 14)); // NOI18N
        jButtonUpdateGrade.setIcon(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Write2.png"))); // NOI18N
        jButtonUpdateGrade.setText("Modificar Calificación");
        jButtonUpdateGrade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonUpdateGradeActionPerformed(evt);
            }
        });

        jLabelOverallGrade.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jLabelOverallGrade.setText("0");

        jLabel2.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jLabel2.setText("Calificacion Acumulada:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPaneNotesTable)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabelSubject)
                .addGap(28, 28, 28)
                .addComponent(jComboBoxSubjects, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonUpdateGrade)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonAddGrade)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonDeleteGrade)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButtonBack)
                    .addComponent(jLabelOverallGrade, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelSubject)
                    .addComponent(jComboBoxSubjects, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPaneNotesTable, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelOverallGrade)
                    .addComponent(jLabel2))
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonBack)
                    .addComponent(jButtonDeleteGrade)
                    .addComponent(jButtonAddGrade)
                    .addComponent(jButtonUpdateGrade))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void fillTable(List<GradesVO> grades) {
        DefaultTableModel mod = (DefaultTableModel) jTableNotes.getModel();

        int a = mod.getRowCount();
        for (int i = 0; i < a; i++) {
            mod.removeRow(0);
        }
        Double total = new Double(0);
        for (GradesVO grade : grades) {
            Object[] row = new Object[5];
            row[0] = grade.getValue();           
            row[1] = new Double(grade.getPercentage()*100).toString();
            row[2] = grade.getType();
            row[3] = grade.getTotal();
            row[4] = grade.getId();
            
            total += grade.getTotal();
            
            mod.addRow(row);
        }
        
        jLabelOverallGrade.setText(total.toString());

        jTableNotes.setModel(mod);
    }

    private void jButtonBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBackActionPerformed
        parent.dispose();
    }//GEN-LAST:event_jButtonBackActionPerformed

    private void jComboBoxSubjectsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxSubjectsActionPerformed
        fillTable(((SubjectVO) jComboBoxSubjects.getSelectedItem()).getGroups().get(0).getGrades());
    }//GEN-LAST:event_jComboBoxSubjectsActionPerformed

    private void jTableNotesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableNotesMouseClicked
        currentRow = jTableNotes.rowAtPoint(evt.getPoint());
    }//GEN-LAST:event_jTableNotesMouseClicked

    private void jButtonAddGradeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddGradeActionPerformed
        AuxiliarFrame aux = new AuxiliarFrame();
        PanelAddGrade panelAddGrade = new PanelAddGrade(aux, jComboBoxSubjects.getSelectedIndex(), PanelAddGrade.ADD, null);
        panelAddGrade.attach(this);
        aux.cambiarPanel(panelAddGrade);
        aux.setVisible(true);
    }//GEN-LAST:event_jButtonAddGradeActionPerformed

    private void jButtonDeleteGradeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteGradeActionPerformed
        if (currentRow >= 0) {
            DefaultTableModel mod = (DefaultTableModel) jTableNotes.getModel();
            int confirm = JOptionPane.showConfirmDialog(this, "En realidad desea eliminar esta calificación?", "Aviso", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                if (new ControlPanelNotes().deleteGrade((int) mod.getValueAt(currentRow, 4))) {
                    JOptionPane.showMessageDialog(this, "Calificación eliminada correctamente", "Aviso", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "La calificación no se ha podido eliminar", "Aviso", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else {
                return;
            }

            if (mod.getRowCount() > 0) {
                mod.removeRow(currentRow);
            }
            currentRow = -1;
        } else {
            JOptionPane.showMessageDialog(this, "Debe seleccionar alguna calificacion primero", "Aviso", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonDeleteGradeActionPerformed

    private void jButtonUpdateGradeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpdateGradeActionPerformed
        if (currentRow >= 0) {
            DefaultTableModel mod = (DefaultTableModel) jTableNotes.getModel();
            AuxiliarFrame aux = new AuxiliarFrame();
            PanelAddGrade panelAddGrade = new PanelAddGrade(aux, jComboBoxSubjects.getSelectedIndex(), PanelAddGrade.UPDATE, new ControlPanelNotes().findGrade((int) mod.getValueAt(currentRow, 4)));
            panelAddGrade.attach(this);
            aux.cambiarPanel(panelAddGrade);
            aux.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this, "Debe seleccionar alguna calificacion primero", "Aviso", JOptionPane.ERROR_MESSAGE);
        }
        currentRow = -1;
    }//GEN-LAST:event_jButtonUpdateGradeActionPerformed

    private void fillComboBoxSubjects() {
        String user = new ControlPanelMyAccount().findByIp().getUsername();
        List<SubjectVO> subjects = new ControlPanelNotes().getSubjectsByUser(user);
        DefaultComboBoxModel comboModel = new DefaultComboBoxModel();
        //comboModel.addElement("Seleccione una materia");
        for (SubjectVO subject : subjects) {
            comboModel.addElement(subject);
        }

        jComboBoxSubjects.setModel(comboModel);
    }
    private int currentRow;
    private AuxiliarFrame parent;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAddGrade;
    private javax.swing.JButton jButtonBack;
    private javax.swing.JButton jButtonDeleteGrade;
    private javax.swing.JButton jButtonUpdateGrade;
    private javax.swing.JComboBox jComboBoxSubjects;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelOverallGrade;
    private javax.swing.JLabel jLabelSubject;
    private javax.swing.JScrollPane jScrollPaneNotesTable;
    private javax.swing.JTable jTableNotes;
    // End of variables declaration//GEN-END:variables

    @Override
    public void update() {
        int currentSubject = jComboBoxSubjects.getSelectedIndex();
        fillComboBoxSubjects();
        jComboBoxSubjects.setSelectedIndex(currentSubject);
        fillTable(((SubjectVO) jComboBoxSubjects.getSelectedItem()).getGroups().get(0).getGrades());
    }
}
